package algorithm.leetcode;

import java.util.LinkedList;

/**
 * @program: util
 * @description: 最近最少使用算法
 * @author: zhouliangliang
 * @create: 2021-05-21 18:02
 **/
public class LRU {

    public void t(LinkedList<Integer> list, int element, int num) {
        while (list.size() > num) {
            list.removeLast();
        }

        if(list.contains(element)) {
            int index = list.indexOf(element);
            list.remove(index);
            list.add(0, element);
        }

        if(!list.contains(element)) {
            list.add(0, element);
        }
    }

    public static void main(String[] args) {
        LRU t = new LRU();
        int []array = new int[]{1,4,2,6,4,5,7,8,3,1};
        LinkedList<Integer> list = new LinkedList<>();
        for(int i=0; i<array.length; i++) {
            t.t(list, array[i], 5);
        }

        list.forEach(item->{
            System.out.println(item);
        });
    }
}
